package service.impl;

import lombok.extern.slf4j.Slf4j;
import service.ClipboardService;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @Author: gaoxu11
 * @Date: 2022/5/13 1:50 AM
 * @Description:GImG.ClipboardServiceImpl
 */
@Slf4j
public class ClipboardServiceImpl implements ClipboardService {
    /**
     * 获取剪切板图片
     *
     * @return
     */
    @Override
    public File getClipboardFile() {
        Image image = null;
        try {
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            Transferable contents = clipboard.getContents(null);
            if (contents == null) {
                log.info("剪切板内容为空");
                return null;
            } else if (contents.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                image = (Image) contents.getTransferData(DataFlavor.imageFlavor);
            }
            BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufferedImage.createGraphics();
            g.drawImage(image, null, null);
            File outputfile = new File("saved.png");
            ImageIO.write(bufferedImage, "png", outputfile);
            return outputfile;

        } catch (Exception e) {
            log.error("ClipboardServiceImpl getClipboardFile [获取剪切板异常]");
        }
        return null;
    }

    /**
     * 复制到剪切板
     *
     * @param text
     * @return
     */
    @Override
    public  boolean writeToClipboard(String text) {
        try {
            Transferable contents = new StringSelection(text);
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(contents, null);
            return true;
        } catch (Exception e) {
            log.error("ClipboardServiceImpl writeToClipboard [粘贴到剪切板异常]");
        }
        return false;
    }
}
